<template>
    <div class="all-list user-manage">
        <el-card class="container mt-5">
            <div slot="header" class="clearfix">
                <span><span class="card-header-box"></span>用户管理</span>
                <a href="javascript:;" class="list-button float-right p-1" @click="logout">登出</a>
                <a href="javascript:;" class="list-button float-right p-1 mr-3" @click="showDialog(0)">添加</a>
            </div>
            <vue-table :data-source="tableList" :queryString="queryModel">
                <template slot="header">
                    <tr>
                        <th scope="col">姓名</th>
                        <th scope="col">用户名</th>
                        <th scope="col">权限</th>
                        <th scope="col">操作</th>
                    </tr>
                </template>
                <template slot="tbody" slot-scope="props">
                    <tr :class=" props.index % 2 == 0 ? 'table-row':''">
                        <td>{{props.item.name}}</td>
                        <td>{{props.item.username}}</td>
                        <td>{{props.item.type}}{{ showSchool(props.item.school_id) }}</td>
                        <td>
                            <el-tooltip content="修改" placement="top" class="mr-3">
                                <img src="../../images/updateimg.png"
                                     v-if="props.item.id !== 4"
                                     @click="showDialog(props.item.id)" height="17" width="17"/>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <img src="../../images/deletedimg.png"
                                     v-if="props.item.id !== 4"
                                     @click="deletedUser(props.item.id)" height="17" width="17"/>
                            </el-tooltip>
                        </td>
                    </tr>
                </template>
            </vue-table>
        </el-card>
        <div class=" mt-5">
            <cplanet-pagination :page-count="tableList.meta.last_page"
                                :total="tableList.meta.total"
                                :current-page="tableList.meta.current_page" @goPage="goPage"></cplanet-pagination>
        </div>


        <el-dialog
                :title="editModelId == 0 ? '新增用户信息' : '修改用户信息'"
                :visible.sync="DialogVisible"
                width="52%"
                >
        <span class="d-block">
            <el-form :model="model" ref="model" :rules="ruleValidate" label-width="85px" style="width: 100%">
                    <el-col :span="10">
                        <el-form-item class="mb-3" label="姓名: " prop="name">
                            <el-input v-model="model.name" placeholder="请输入姓名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="2">
                        <el-form-item class="mb-3" label="用户名: " prop="username">
                            <el-input v-model="model.username" placeholder="请输入用户名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item class="mb-3" label="密码: " prop="password">
                            <el-input v-model="model.password" placeholder="请输入密码"></el-input>
                        </el-form-item>
                    </el-col>
                    <!--<el-col :span="10" :offset="2">-->
                        <!--<el-form-item class="mb-3" label="确认密码: " prop="password">-->
                            <!--<el-input v-model="model.confirmPassword" placeholder="请输入密码"></el-input>-->
                        <!--</el-form-item>-->
                    <!--</el-col>-->

                    <el-col :span="10" :offset="2">
                        <el-form-item class="mb-3" label="性别: " prop="sex">
                            <el-radio class="mt-2" v-model="model.sex" label="男">男</el-radio>
                            <el-radio class="mt-2" v-model="model.sex" label="女">女</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item class="mb-3" label="身份: " prop="type">
                            <el-radio class="mt-2" v-model="model.type" label="admin">admin</el-radio>
                            <el-radio class="mt-2" v-model="model.type" label="录入">录入</el-radio>
                            <el-radio class="mt-2" v-model="model.type" label="编辑">编辑</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="2" style="height: 64px">
                        <el-form-item class="mb-3 all-select" v-show="model.type !== 'admin'" label="学校: " prop="school_id">
                            <el-select v-model="model.school_id" placeholder="请选择学校" clearable style="width: 100%">
                                    <el-option v-for="item in schoolNameList"
                                               :key="item.id" :label="item.name" :value="item.id">
                                    </el-option>
                                </el-select>
                        </el-form-item>
                    </el-col>
                    <!--<el-col :span="10" :offset="2" v-else style="height: 64px">-->
                        <!--<el-form-item class="mb-3" label=" " >-->

                        <!--</el-form-item>-->
                    <!--</el-col>-->
            </el-form>
        </span>
           <span slot="footer" class="dialog-footer" style="position: relative;bottom: 0;">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" @click="Dialogsave">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
  import ListDataSource from '../libs/ListDataSource.js'
  import DataApi from '../api/data'
  import Cookie from 'js-cookie';
  export default {
    data(){
      return{
        tableList: new ListDataSource('/api/user'),
        queryModel:{},
        DialogVisible: false,
        model: {
            id: 0,
            name: '',
            username: '',
            type: 'admin',
//            password: '',
            sex: '',
            school_id: ' ',
//            api_token:''
//            confirmPassword:''
        },
        ruleValidate:{
          name: [
            {required: true, message: '此项目为必填项', trigger: 'blur'}
          ],
          username: [
            {required: true, message: '此项目为必填项', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '此项目为必填项', trigger: 'blur'}
          ],
//          password: [
//            {required: true, message: '此项目为必填项', trigger: 'blur'}
//          ],
//          confirmPassword: [
//            {required: true, message: '此项目为必填项', trigger: 'blur'}
//          ],
          sex: [
            {required: true, message: '此项目为必填项', trigger: 'blur'}
          ],
          school_id: [
            {required: true, message: '此项目为必填项', trigger: 'blur'}
          ],
        },
        schoolNameList:[
          {name:'第一幼儿园',id:'101'},
          {name:'第二幼儿园',id:'102'},
          {name:'第四幼儿园',id:'104'},
          {name:'模范幼儿园',id:'106'},
          {name:'第三幼儿园',id:'103'},
          {name:'第五幼儿园',id:'105'}
        ],
        refreshList: false,
        editModelId: 0
      }
    },
    created () {
      let vm = this
      this.isLoading = true
      Promise.all([
        vm.tableList.fetchData()
      ]).then(([Response]) => {
        vm.isLoading = false
      }).catch((error) => {
        vm.isLoading = false
      })
      console.log(vm.tableList)
    },
    methods: {
      goPage: function (event) {
        let self = this
        let query = _.assign({page: event.page}, self.queryString);
        self.tableList.fetchData(query)
      },
      showDialog(id){
        this.DialogVisible = true
        this.editModelId = id
        console.log(this.model)
      },
      closeDialog(){
        this.DialogVisible = false
        this.editModelId = 0
      },
      deletedUser(id){
        let self = this
        if (self.user.id !== id) {
          this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
//            self.model.uuid = id
//            self.model.destroy(function () {
              DataApi.DeletedUserInfo(id).then(res=>{
              self.$message.success('删除成功!')
              self.refreshList = !self.refreshList
            });
          }).catch(() => {
            self.$message({
              type: 'info',
              message: '取消删除'
            });
          });
        }else {
          self.$message.error('不能删除自己!')
        }
      },
      Dialogsave(){
        let self = this
        console.log(self.model)
        self.$refs['model'].validate((valid) => {
          if (valid) {
            console.log('表单验证通过')
            let uuid = self.model.id ? self.model.id : 0
            if(uuid === 0) {
              DataApi.postUserInfo(self.model).then(res => {
                self.$message.success(self.model.name + '保存成功');
                self.refreshList = !self.refreshList
                self.closeDialog()
              }).catch(err => {
                self.$message.error('保存失败')
              })
            }else {
              DataApi.putUserInfo(uuid,self.model).then(res => {
                self.$message.success(self.model.name + '修改成功');
                self.refreshList = !self.refreshList
                self.closeDialog()
              }).catch(err => {
                self.$message.error('保存失败')
              })
            }
          } else {
          }
        })
      },
      logout(){
        axios.post('/api/logout', {})
          .then(function (response) {
            Cookie.remove('user');
            window.location.reload();
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      showSchool(school_id){
        switch (school_id)
        {
          case '101':
            return '—第一幼儿园'
          break
          case '102':
            return '—第二幼儿园'
          break
          case '104':
            return '—第四幼儿园'
          break
          case '106':
            return '—模范幼儿园'
          break
          case '103':
            return '—第三幼儿园'
          break
          case '105':
            return '—第五幼儿园'
          break
          default:
            return ''
        }
      }
    },
    computed:{
      user(){
        return this.$store.state.user
      }
    },
    watch:{
        'editModelId':function(value){
          let self = this
          if (value != 0) {
            DataApi.getUserInfo(value).then(res => {
              console.log(res)
              self.model = res.data.data
            })
          }
          console.log(this.model)
        },
      'refreshList':function(){
        this.tableList.fetchData()
      },
      'DialogVisible':function (value) {
        if (!value) {
          this.model = {
            id: 0,
            name: '',
            username: '',
            type: 'admin',
            sex: '',
            school_id:  ' ',
          }
        }
      }
    }
  }
</script>
